package com.gl.emms.whale.wxapi;

import com.gl.emms.client.android.EMMSPushManager;
import com.gl.emms.nio.mutual.ReplyBody;
import com.gl.emms.whale.R;
import com.gl.emms.whale.app.Constant;
import com.gl.emms.whale.app.MyApplication;
import com.gl.emms.whale.app.WhaleMonitorActivity;
import com.gl.emms.whale.ui.RechargeRecordActivity;
import com.gl.emms.whale.util.RechargeRecordEntity;
import com.gl.emms.whale.util.SharePreferenceUtil;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import android.content.Intent;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**微信支付 必须为这个名
 * @author ganlinux
 *
 */
public class WXPayEntryActivity extends WhaleMonitorActivity implements IWXAPIEventHandler{
	//支付记录实体
	private RechargeRecordEntity rechargeRecordEntity;
	private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";
	
	private Button recharge_btn;//支付按钮
	private IWXAPI api;//微信支付api类
	private TextView rechargeResultText;
	private String money;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharePreferenceUtil util = new SharePreferenceUtil(this, Constant.SAVE_BILL);
		money = util.getMoney();
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		setContentView(R.layout.pay_result);

		Button titleBackBtn = (Button)findViewById(R.id.TitleBackBtn);  
		titleBackBtn.setOnClickListener(new OnClickListener() {  
			public void onClick(View v) {  
				KeyEvent newEvent = new KeyEvent(KeyEvent.ACTION_DOWN,  
						KeyEvent.KEYCODE_BACK);
				finish();
				//mActivity.onKeyDown(KeyEvent.KEYCODE_BACK, newEvent);  
			}  
		});
		recharge_btn = (Button)findViewById(R.id.rechargerecord_btn);  
		recharge_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.rechargerecord_btn:
					Intent rechargeRecordActivity = new Intent(WXPayEntryActivity.this,RechargeRecordActivity.class);  
					startActivity(rechargeRecordActivity);
					break;

				default:
					break;
				}
			}
		});

		api = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
		api.handleIntent(getIntent(), this);
		
		rechargeResultText = (TextView) findViewById(R.id.rechargeresult_text);

		
		rechargeRecordEntity = new RechargeRecordEntity();
	}
	@Override
	public void initViews() {
		// TODO Auto-generated method stub
		
	};
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);

		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

			//AlertDialog.Builder builder = new AlertDialog.Builder(this);
			//builder.setTitle("提示");
			//builder.setMessage(String.format("微信支付结果：%s", String.valueOf(resp.errCode)));
			//builder.show();
			Message message = new Message();    
			if (resp.errCode == 0) 
			{
				message.what = 0x05;   
			}else
			{
				message.what = 0x04;
				//向数据库中添加失败记录
			}
			handler.sendEmptyMessage(message.what);
		}
	}
	Handler handler = new Handler(){  
		public void handleMessage(Message msg) {  
			switch (msg.what) {      
			case 0x04: 
				rechargeResultText.setText("您已取消支付");
				break;  
			case 0x05: 
				//String bill = UUID.randomUUID().toString().replaceAll("-","");
				rechargeResultText.setText("您已支付成功，请等待为您充值");
				//rechargeRecordEntity = new RechargeRecordEntity(bill, "0.01", "2014", "1", MyApplication.getUserData().getName());
				//EMMSPushManager.requestRecharge(WXPayEntryActivity.this,MyApplication.getUserData().getId(),MyApplication.getUserData().getName(),MyApplication.getUserData().getMainroom(),"12345","0.01");
				rechargeRecordEntity.setMoney(money);
				EMMSPushManager.requestSelectRecharge(WXPayEntryActivity.this, MyApplication.getUserData().getIdIP(), MyApplication.getUserData().getMainroom());
				break;  
			case 0x06:
				String balance= rechargeRecordEntity.getBalance();
				String cardnum= MyApplication.getUserData().getCardnum();
				//EMMSPushManager.requestRecharge(WXPayEntryActivity.this,MyApplication.getUserData().getIdIP(),MyApplication.getUserData().getName(),MyApplication.getUserData().getMainroom(),rechargeRecordEntity.getBill(),money,balance,cardnum);
				EMMSPushManager.requestRecharge(WXPayEntryActivity.this,MyApplication.getUserData().getIdIP(),MyApplication.getUserData().getName(),MyApplication.getUserData().getMainroom(),"123",money,balance,cardnum);
				break;
			case 0x07:
				showToask("充值成功");
				//rechargeRecordEntity.setState("0");
				//RechargeRecordDB rechargeRecordDB = new RechargeRecordDB(WXPayEntryActivity.this);
				//rechargeRecordDB.saveRecord(rechargeRecordEntity);// 保存到数据库 
				//rechargeRecordDB.close();
				break;
			case 0x08:
				showToask("充值失败");
				break;
			default:
				break;
			}      
			super.handleMessage(msg);  
		}    
	}; 
	@Override
	public void onReplyReceived(final ReplyBody reply) {
		super.onReplyReceived(reply);
		if (reply.getType().equals("recharge_response")) {
			if(reply.get("rechargestate").equals("000000"))
			{
				Message message = new Message();    
				message.what = 0x07;   
				handler.sendEmptyMessage(message.what);
			}else
			{
				Message message = new Message();    
				message.what = 0x08;   
				handler.sendEmptyMessage(message.what);
			}
			//rechargeRecordEntity.setState("0");
			//RechargeRecordDB rechargeRecordDB = new RechargeRecordDB(this);
			//rechargeRecordDB.saveRecord(rechargeRecordEntity);// 保存到数据库 
			//rechargeRecordDB.close();
		}else if (reply.getType().equals("rechargesync_response")) {
			if(reply.get("rechargestate").equals("000000"))
			{
				Message message = new Message();    
				message.what = 0x07;   
				handler.sendEmptyMessage(message.what);
				
			}else
			{
				Message message = new Message();    
				message.what = 0x08;   
				handler.sendEmptyMessage(message.what);
				
			}
		}else if (reply.getType().equals("selectcharge_response")) {
			if(reply.get("state").equals("000000"))
			{
				rechargeRecordEntity.setBalance(reply.get("recharge"));
				Message message = new Message();    
				message.what = 0x06;   
				handler.sendEmptyMessage(message.what);

			}else
			{
				showToask("充值失败");
			}
		}
	}
	
	@Override
	public void onConnectionSucceed()//重连由loginactivity 负责
	{
	}
	@Override
	public void onConnectionStatus(boolean  isConnected){}//网络状态改变由loginactivity 负责
	@Override
	public   void onNetworkChanged(NetworkInfo info){
	}

	
	
	
}